import 'package:mobx/mobx.dart';
import '../models/share_comment_model.dart';
import '../services/share_comment_service.dart';
import 'auth_store.dart';

part 'share_comment_store.g.dart';

class ShareCommentStore = _ShareCommentStore with _$ShareCommentStore;

abstract class _ShareCommentStore with Store {
  final ShareCommentService _service = ShareCommentService();
  final AuthStore _authStore;

  _ShareCommentStore(this._authStore);

  @observable
  ObservableList<ShareCommentModel> comments =
      ObservableList<ShareCommentModel>();

  @observable
  bool isLoading = false;

  @observable
  String? errorMessage;

  @action
  Future<void> loadComments(String shareId) async {
    isLoading = true;
    errorMessage = null;
    try {
      final list = _service.getCommentsByShareId(shareId);
      comments.clear();
      comments.addAll(list);
      isLoading = false;
    } catch (e) {
      errorMessage = 'load comments failed:  ${e.toString()}';
      isLoading = false;
    }
  }

  @action
  Future<void> addComment(String shareId, String content) async {
    if (_authStore.currentUser == null) throw Exception('not login');
    isLoading = true;
    errorMessage = null;
    try {
      await _service.addComment(
        shareId: shareId,
        userId: _authStore.currentUser!.id,
        content: content,
      );
      await loadComments(shareId);
      isLoading = false;
    } catch (e) {
      errorMessage = 'add comment failed: ${e.toString()}';
      isLoading = false;
    }
  }
}
